package controller;


import helper.Calendr;
import helper.Formatter;
import helper.UserSession;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;

import databeans.Customer;
import databeans.Employee;
import databeans.Fund;
import databeans.FundHistory;
import model.FundDAO;
import model.FundHistoryDAO;
import model.Model;

public class EmployeeCreateFundHistoryAction extends Action{
    private FundDAO fundDAO;
    private FundHistoryDAO fundHistoryDAO;

    public EmployeeCreateFundHistoryAction(Model model) {
        fundDAO = model.getFundDAO();
        fundHistoryDAO = model.getFundHistoryDAO();
    }
    
    public String getName() {
        return "employeeCreateFundHistory.do";
    }
    

    public String perform(HttpServletRequest request) {
        //ATTENTION
        // define target page
        String loginPage = "employee/login-form.jsp";
        String dashboardPage = "employee/employee-dashboard.jsp";
        //String viewFundsPage = "employee/view-funds.jsp";
        String originPage = "employee/create-fund-history-form.jsp";
        String successPage = dashboardPage; 
        
        //set the employee
        Employee employee = null;
        Customer customer = null;
        Fund fund = null;
        FundHistory fundHistory = null;

        //errors and messages will be stored here
        //resetting those containers
        List<String> errors = new ArrayList<String>();
        List<String> messages = new ArrayList<String>();
   
        //define the error and message
        request.setAttribute("errors", errors);
        request.setAttribute("messages", messages);
        
        //get all the parameter from the form
        String requestType = request.getParameter("Submit");      
        String fundID = request.getParameter("fundID");
        String priceDate = request.getParameter("txtPriceDate");
        String price = request.getParameter("txtPrice");
        //String fundSymbol = request.getParameter("txtFundPrice");
  
        //reload the form field
        request.setAttribute("fundID", fundID);
        request.setAttribute("txtPriceDate", priceDate);
        request.setAttribute("txtPrice", price);

        //check if employee has been logged in
        //request.getSession() will return the current session and if one does not exist, a new session will be cretaed.
        //request.getSession(true) will return the current session if one exists, if one doesn't exits a new one will be created.
        //So there is actually no difference between the two methods HOWEVER, if you use request.getSession(false), it will return the current session if one exists and if one DOES NOT exist a new one will NOT be cretaed.
        employee = UserSession.getLoggedInEmployee(request);
        if (employee == null) {
            errors.add("You need to log in");
            return loginPage ;
        }
        
        //check if customer has actually logged in
        customer = UserSession.getLoggedInCustomer(request);
        if (customer != null) {
            request = UserSession.removeCustomerFromSession(request);
            errors.add("This section is closed for customer");
            return loginPage;
        }

        // check for get or post request
        //if there is no parameter get passed, return to origin page
        if (fundID == null || fundID.equals("")) {
            messages.add("Select fund below");
            return "employeeViewFunds.do";     
        }
        
        if (requestType == null) {
            request.setAttribute("fundID", fundID);
            messages.add("To create Fund history, fill the form below");
            return originPage;     
        }
        
        if (fundID != null && priceDate == null && price == null){
            messages.add("To create Fund history, fill the form below");
            return originPage;   
        }
        
        if (priceDate == null || priceDate.trim().equals("")){
            messages.add("You should add the date");
            errors.add("Current price date is still empty");
            return originPage;   
        }
        
        //TODO more validation for DATE and DOUBLE
        //TODO change the validation on other controller action to be like this
        
        if (price == null || price.trim().equals("")){
            messages.add("You should add the price");
            errors.add("Current price is still empty");
            return originPage;   
        }
        
      //check if double value inputted is A double
        if (!Formatter.isDouble(price)){
            //messages.add("You must input a number in amount field");
            errors.add("Invalid input in price field. Please check.");
            return originPage;
        }
        
        //check if double has 2 decimal place
        if(Formatter.numberOfDecimal(price)>2) {
            messages.add("CFA only tracks amount up to two decimal place. Please reenter the amount");
            errors.add("Accuracy could not be captured");
            return originPage;
        }
        

        
        //ensure no negative number
        if ( Double.parseDouble(price) <= 0.00 ){
            //messages.add("The amount should not be negative");
            errors.add("Invalid input for Number of Shares to purchase. Please check.");
            return originPage;
        }


        try {
            fund = fundDAO.lookup(Integer.parseInt(fundID));
        } catch (DAOException e2) {
            messages.add("You must select available fund");
            errors.add("Fund could not be retrieved " + fundID);
            return originPage;
        }
        

        
        // at this stage, all input validation should have been done
        try {
            


            fundHistory = new FundHistory();
            fundHistory.setFundID(Integer.parseInt(fundID));
            fundHistory.setPriceDate(Calendr.parseTimestamp(priceDate));
            fundHistory.setPrice(Formatter.prepCashFromView(price));
            
            
            fundHistoryDAO.create(fundHistory);
            
            // Attach (this copy of) the logged in employee bean to the session
            HttpSession session = request.getSession(true); 
            Employee loggedInEmployee = (Employee) session.getAttribute("employee");
            session.setAttribute("employee", loggedInEmployee );
            
            //set the welcome message
            messages.add("Hi " + loggedInEmployee.getFirstName() + "!, you have succesfully created new fundhistory " + fundHistory.getFundID() + " (" + fundHistory.getPriceDate().toString() + ")");
            return successPage;

        } catch (Exception e) {
            errors.add("Unable to create new fund history");
            errors.add("msg:" + e.getClass().toString() + "-" +  e.getMessage() +"-"+ e.getLocalizedMessage());
            try {
                errors.add("fundid: " + fundID + "/pricedateparsed:" + Calendr.parseTimestamp(priceDate) + "/price:" + price);
            } catch (Exception e1) {
                errors.add("msge1:"+ e1.getClass().toString() + "-" + e.getMessage());
                e1.printStackTrace();
            }
            return dashboardPage;
        }

    }
    

}